package com.hjy.controller;

import com.hjy.entity.Users;
import com.hjy.serivce.UsersServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
public class UsersController {

    @Resource
    private UsersServiceImpl usersService;

    public UsersServiceImpl getUsersService() {
        return usersService;
    }

    public void setUsersService(UsersServiceImpl usersService) {
        this.usersService = usersService;
    }

   /* @RequestMapping("/text")
    public String text(){
        return JSONArray.toJSONString(usersService.findByUsersName("admin"));
    }*/

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping("/logout")
    public String logout(){
        Subject subject=SecurityUtils.getSubject();
        if (subject!=null){
            subject.logout();
        }
        return "redirect:/login";
    }
    @GetMapping
    @ResponseBody
    public String admin(){
        return "只有admin才能看到的";
    }

    //登陆认证
    @RequestMapping("/loginUser")
    public String loginUsers(@RequestParam("username")String username,
                             @RequestParam("password")String password,
                             HttpServletRequest request){
        //传入用户名和密码进去
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
        Subject subject=SecurityUtils.getSubject();
        try {
            //开始认证，若出错则会catch
            subject.login(usernamePasswordToken);
            //获得对象
            Users users=(Users) subject.getPrincipal();
            //把对象放入session内
            request.getSession().setAttribute("users",users);
            //成功则返回index页面
            return "redirect:/index";
        } catch (Exception e) {
            //失败则返回到login页面
            return "redirect:/login";
        }
    }

    @GetMapping("/edit")
    @ResponseBody
    public String edit(){
        return "edit返回信息";
    }

    @GetMapping("unauthorized")
    public String unauthorized(){
        return "unauthorized";
    }
}
